/**
 * IndexCtrl.java   2017年4月14日 下午4:46:27 by xuebing 
 *
 * Copyright (c) 2010 - 2017 All rights reserved.
 * 
 */
package com.rongmai.web.ctrl;

import com.rongmai.db.dto.UserAndCompanyDTO;
import com.rongmai.db.exception.BzException;
import com.rongmai.db.model.BaseResult;
import com.rongmai.db.model.User;
import com.rongmai.db.vo.UserVo;
import com.rongmai.web.bo.UserBo;
import com.rongmai.web.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserCtrl {

    @Resource
    private UserBo userBo;

    @RequestMapping(value="/edit", method = RequestMethod.POST)
    public BaseResult edit(@RequestBody UserAndCompanyDTO userAndCompanyDTO, HttpServletRequest request) {
        if (userAndCompanyDTO == null || userAndCompanyDTO.getDepartmentLabelId() == null || userAndCompanyDTO.getRole() == null) {
            return BaseResult.fail("参数非法");
        }
        try {
            User currentUser = UserUtils.getCurrentUser(request);
            if (currentUser == null) {
                log.error("登录用户不存在");
                return BaseResult.FAIL;
            }
            userAndCompanyDTO.setMobile(currentUser.getMobile());
            userBo.updateCompanyAndUser(userAndCompanyDTO);
        } catch (BzException e) {
            log.error("更新用户异常", e);
            return BaseResult.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新用户异常", e);
            return BaseResult.FAIL;
        }

        return BaseResult.SUCCESS;
    }

    @RequestMapping("getUser")
    public BaseResult<List<UserVo>> getUser(String mobile) {
        return BaseResult.succ(userBo.getByMobile(mobile));
    }

    @RequestMapping("getUniqueUser")
    public BaseResult<UserVo> getUniqueUser(String mobile, String role) {
        return BaseResult.succ(userBo.getUniqueUser(mobile, role));
    }

    @RequestMapping(value="/my_department_user", method = RequestMethod.GET)
    public BaseResult<List<UserVo>> myDepartmentUser(Integer departmentId){
        try {
            return BaseResult.succ(userBo.myDepartmentUser(departmentId));
        } catch (Exception e) {
            log.error("搜索异常", e);
        }
        return BaseResult.FAIL;
    }

    @RequestMapping(value="/my_company_user", method = RequestMethod.GET)
    public BaseResult<List<UserVo>> myCompanyUser(Integer companyId){
        try {
            return BaseResult.succ(userBo.myCompanyUser(companyId));
        } catch (Exception e) {
            log.error("搜索异常", e);
        }
        return BaseResult.FAIL;
    }


}
